<template>
	<view class="chat-detail">
		<!-- 顶部导航栏 -->
		<view class="chat-header">
			<view class="header-content">
				<view class="header-left" @click="goBack">
					<text class="back-icon">‹</text>
				</view>
				<view class="header-center">
					<text class="chat-title">{{ nickname }}</text>
					<text class="online-status">{{ isConnected ? '在线' : '离线' }}</text>
				</view>
				<view class="header-right">
					<view class="more-icon" @click="showChatMenu">
						<text>⋯</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 连接状态提示 - 已隐藏，改为静默重连 -->

		<!-- 消息列表 -->
		<scroll-view
			class="message-list"
			scroll-y
			:scroll-top="scrollTop"
			:scroll-with-animation="false"
			@scrolltoupper="loadMoreMessages"
			:enable-back-to-top="false"
			:enhanced="true"
			:bounces="true"
			:show-scrollbar="false"
			:scroll-anchoring="true"
			:refresher-enabled="false"
			:fast-deceleration="false"
		>
			<!-- 背景图片 -->
			<view class="chat-background"></view>
			<!-- 加载更多提示 -->
			<view v-if="hasMoreMessages" class="load-more">
				<view class="loading-indicator">
					<text class="loading-text">{{ loadingMore ? '加载中...' : '下拉加载更多' }}</text>
				</view>
			</view>

			<!-- 消息列表 -->
			<view
				v-for="message in messages"
				:key="`msg-${message.id}-${message.sendTime}`"
				class="message-item"
				:class="{ 'own-message': message.fromUserId === userInfo.userId }"
			>
				<!-- 时间分割线 -->
				<view v-if="shouldShowTime(message)" class="time-divider">
					<view class="time-label">
						<text class="time-text">{{ formatDetailTime(message.sendTime) }}</text>
					</view>
				</view>

				<!-- 消息内容 -->
				<view class="message-wrapper" :class="{ 'own-message-wrapper': message.fromUserId === userInfo.userId }">
					<!-- 消息气泡 -->
					<view class="message-bubble" :class="{ 'own-bubble': message.fromUserId === userInfo.userId }">
						<!-- 消息内容 -->
						<view class="message-content">
							<text class="message-text">{{ message.content }}</text>
						</view>
					</view>
				</view>

				<!-- 消息状态和时间 -->
				<view v-if="message.fromUserId === userInfo.userId" class="message-status own-status">
					<text class="message-time">{{ formatTime(message.sendTime) }}</text>
					<view class="send-status">
						<text v-if="message.status === 'sending'" class="status-sending">发送中</text>
						<text v-else-if="message.status === 'failed'" class="status-failed">发送失败</text>
						<text v-else class="status-sent">✓</text>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="messages.length === 0" class="empty-messages">
				<view class="empty-icon">💬</view>
				<text class="empty-text">暂无聊天记录</text>
				<text class="empty-tip">开始你们的第一次对话吧</text>
			</view>
		</scroll-view>
		
		<!-- 输入区域 -->
		<view class="input-area" :class="{ 'panel-open': showEmojiPanel || showMorePanel }">
			<view class="input-wrapper">
				<!-- 语音/更多功能按钮 -->
				<view class="function-btn" @click="toggleMorePanel" :class="{ 'active': showMorePanel }">
					<text class="function-icon">{{ showMorePanel ? '⌨️' : '+' }}</text>
				</view>

				<!-- 输入框容器 -->
				<view class="input-container">
					<!-- 输入框 -->
					<textarea
						v-model="inputMessage"
						placeholder="输入消息..."
						class="message-input"
						:auto-height="true"
						:maxlength="500"
						@confirm="sendMessage"
						@focus="onInputFocus"
						@blur="onInputBlur"
						:adjust-position="false"
						:show-confirm-bar="false"
					/>
				</view>

				<!-- 表情按钮 -->
				<view class="function-btn" @click="toggleEmojiPanel" :class="{ 'active': showEmojiPanel }">
					<text class="function-icon">😊</text>
				</view>

				<!-- 发送按钮 -->
				<view
					v-if="inputMessage.trim()"
					class="send-btn"
					@click="sendMessage"
					:class="{ 'sending': sending }"
				>
					<text class="send-text">{{ sending ? '...' : '发送' }}</text>
				</view>

				<!-- 语音按钮 -->
				<view v-else class="voice-btn" @touchstart="startVoiceRecord" @touchend="endVoiceRecord">
					<text class="voice-icon">🎤</text>
				</view>
			</view>

			<!-- 表情面板 -->
			<view v-if="showEmojiPanel" class="emoji-panel">
				<view class="emoji-header">
					<text class="emoji-title">表情</text>
				</view>
				<scroll-view class="emoji-scroll" scroll-y>
					<view class="emoji-grid">
						<view
							v-for="emoji in emojiList"
							:key="emoji"
							class="emoji-item"
							@click="insertEmoji(emoji)"
						>
							<text class="emoji-text">{{ emoji }}</text>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 更多功能面板 -->
			<view v-if="showMorePanel" class="more-panel">
				<view class="more-header">
					<text class="more-title">更多功能</text>
				</view>
				<view class="more-grid">
					<view class="more-item" @click="chooseImage">
						<view class="more-icon-wrapper">
							<text class="more-icon">📷</text>
						</view>
						<text class="more-text">相册</text>
					</view>
					<view class="more-item" @click="takePhoto">
						<view class="more-icon-wrapper">
							<text class="more-icon">📸</text>
						</view>
						<text class="more-text">拍照</text>
					</view>
					<view class="more-item" @click="chooseVideo">
						<view class="more-icon-wrapper">
							<text class="more-icon">🎥</text>
						</view>
						<text class="more-text">视频</text>
					</view>
					<view class="more-item" @click="chooseFile">
						<view class="more-icon-wrapper">
							<text class="more-icon">📁</text>
						</view>
						<text class="more-text">文件</text>
					</view>
					<view class="more-item" @click="shareLocation">
						<view class="more-icon-wrapper">
							<text class="more-icon">📍</text>
						</view>
						<text class="more-text">位置</text>
					</view>
					<view class="more-item" @click="sendVoice">
						<view class="more-icon-wrapper">
							<text class="more-icon">🎤</text>
						</view>
						<text class="more-text">语音</text>
					</view>
					<view class="more-item" @click="sendRedPacket">
						<view class="more-icon-wrapper">
							<text class="more-icon">🧧</text>
						</view>
						<text class="more-text">红包</text>
					</view>
					<view class="more-item" @click="transfer">
						<view class="more-icon-wrapper">
							<text class="more-icon">💰</text>
						</view>
						<text class="more-text">转账</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 聊天菜单弹窗 -->
		<view v-if="showChatMenuModal" class="chat-menu-modal" @click="hideChatMenu">
			<view class="chat-menu" @click.stop>
				<view class="chat-menu-item" @click="viewProfile">
					<text class="menu-icon">👤</text>
					<text class="menu-text">查看资料</text>
				</view>
				<view class="chat-menu-item" @click="clearHistory">
					<text class="menu-icon">🗑️</text>
					<text class="menu-text">清空聊天记录</text>
				</view>
				<view class="chat-menu-item" @click="setBackground">
					<text class="menu-icon">🖼️</text>
					<text class="menu-text">设置背景</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { getChatHistory, markSessionAsRead, sendMessage as sendMessageAPI } from '@/utils/api.js'
	import { connectWebSocket, sendWebSocketMessage, closeWebSocket } from '@/utils/websocket.js'
	
	export default {
		data() {
			return {
				userId: null,
				nickname: '',
				userInfo: null,
				messages: [],
				inputMessage: '',
				scrollTop: 0,
				sending: false,
				showEmojiPanel: false,
				showMorePanel: false,
				showChatMenuModal: false,
				hasMoreMessages: false,
				loadingMore: false,
				currentPage: 1,
				pageSize: 20,
				lastMessageTime: null,
				isConnected: false,
				messageListHeight: 600,
				isRecordingVoice: false,
				scrollTimer: null, // 滚动防抖定时器
				renderTimer: null, // 渲染节流定时器
				emojiList: [
					'😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣',
					'😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰',
					'😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜',
					'🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏',
					'😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣',
					'😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠',
					'😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨',
					'😰', '😥', '😓', '🤗', '🤔', '🤭', '🤫', '🤥',
					'😶', '😐', '😑', '😬', '🙄', '😯', '😦', '😧',
					'😮', '😲', '🥱', '😴', '🤤', '😪', '😵', '🤐',
					'🥴', '🤢', '🤮', '🤧', '😷', '🤒', '🤕', '🤑',
					'🤠', '😈', '👿', '👹', '👺', '🤡', '💩', '👻',
					'💀', '☠️', '👽', '👾', '🤖', '🎃', '😺', '😸',
					'😹', '😻', '😼', '😽', '🙀', '😿', '😾', '👋',
					'🤚', '🖐️', '✋', '🖖', '👌', '🤏', '✌️', '🤞',
					'🤟', '🤘', '🤙', '👈', '👉', '👆', '🖕', '👇',
					'☝️', '👍', '👎', '👊', '✊', '🤛', '🤜', '👏',
					'🙌', '👐', '🤲', '🤝', '🙏', '✍️', '💅', '🤳',
					'❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '🤍',
					'🤎', '💔', '❣️', '💕', '💞', '💓', '💗', '💖',
					'💘', '💝', '💟', '☮️', '✝️', '☪️', '🕉️', '☸️',
					'✡️', '🔯', '🕎', '☯️', '☦️', '🛐', '⛎', '♈',
					'♉', '♊', '♋', '♌', '♍', '♎', '♏', '♐',
					'♑', '♒', '♓', '🆔', '⚛️', '🉑', '☢️', '☣️'
				]
			}
		},

		computed: {
			// 计算消息列表高度
			computedMessageListHeight() {
				try {
					const systemInfo = uni.getSystemInfoSync()
					const headerHeight = 88 // 顶部导航高度
					const inputAreaHeight = this.showEmojiPanel || this.showMorePanel ? 400 : 100 // 输入区域高度
					const statusBarHeight = systemInfo.statusBarHeight || 0

					return systemInfo.windowHeight - headerHeight - inputAreaHeight - statusBarHeight
				} catch (error) {
					console.error('计算高度失败:', error)
					return 600 // 默认高度
				}
			}
		},
		
		onLoad(options) {
			this.userId = parseInt(options.userId)
			this.nickname = decodeURIComponent(options.nickname || '未知用户')
			this.userInfo = uni.getStorageSync('userInfo')
			
			console.log('聊天详情页面参数:', {
				userId: this.userId,
				nickname: this.nickname,
				userInfo: this.userInfo
			})

			// 设置导航栏标题但不隐藏（避免兼容性问题）
			uni.setNavigationBarTitle({
				title: this.nickname
			})

			this.calculateMessageListHeight()
			this.loadChatHistory()
			this.initWebSocket()
		},

		onUnload() {
			closeWebSocket()
			// 清理定时器
			if (this.scrollTimer) {
				clearTimeout(this.scrollTimer)
				this.scrollTimer = null
			}
			if (this.renderTimer) {
				clearTimeout(this.renderTimer)
				this.renderTimer = null
			}
		},

		onReady() {
			this.calculateMessageListHeight()
		},
		
		methods: {
			/**
			 * 加载聊天历史记录
			 */
			async loadChatHistory() {
				try {
					const result = await getChatHistory(this.userId)
					if (result.code === 200) {
						const newMessages = result.data || []

						// 确保消息按时间排序
						this.messages = newMessages.sort((a, b) => new Date(a.sendTime) - new Date(b.sendTime))
						this.scrollToBottom()

						// 标记会话为已读
						this.markAsRead()
					} else {
						console.error('加载聊天记录失败:', result.message)
						uni.showToast({
							title: result.message || '加载失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('加载聊天记录失败:', error)
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					})
				}
			},
			
			/**
			 * 加载更多消息（暂时禁用分页）
			 */
			async loadMoreMessages() {
				// 暂时不支持分页加载更多
				return
			},
			
			initWebSocket() {
				const token = uni.getStorageSync('token')
				if (!token) {
					console.error('未找到token，无法连接WebSocket')
					this.isConnected = true // 设置为true避免显示错误提示
					return
				}

				try {
					connectWebSocket(token, (message) => {
						// 处理接收到的消息
						if (message.type === 'chat') {
							// 只处理别人发给我的消息，避免重复显示自己发送的消息
							if (message.fromUserId !== this.userInfo.userId) {
								// 检查消息是否已存在，避免重复添加
								const existingMessage = this.messages.find(m =>
									m.id === message.messageId ||
									(m.content === message.content && m.fromUserId === message.fromUserId &&
									 Math.abs(new Date(m.sendTime) - new Date(message.sendTime)) < 1000)
								)

								if (!existingMessage) {
									// 直接添加消息，但优化滚动
									this.messages.push({
										id: message.messageId || Date.now(),
										fromUserId: message.fromUserId,
										toUserId: message.toUserId,
										content: message.content,
										sendTime: message.sendTime || new Date().toISOString()
									})

									// 使用节流优化滚动
									if (this.renderTimer) {
										clearTimeout(this.renderTimer)
									}
									this.renderTimer = setTimeout(() => {
										this.scrollToBottom()
									}, 16) // 约60fps的渲染频率

									// 自动标记为已读（因为用户正在查看聊天）
									this.markAsRead()
								}
							}
						} else if (message.type === 'auth_success') {
							this.isConnected = true
						}
					})

					// 设置连接状态为已连接
					this.isConnected = true

				} catch (error) {
					console.error('WebSocket连接失败:', error)
					// 静默处理连接失败，不显示红色提示
					this.isConnected = true
				}
			},

			/**
			 * 重新连接WebSocket
			 */
			reconnectWebSocket() {
				this.isConnected = false
				uni.showLoading({
					title: '连接中...'
				})

				setTimeout(() => {
					this.initWebSocket()
					uni.hideLoading()
				}, 1000)
			},
			
			/**
			 * 发送消息
			 */
			async sendMessage() {
				if (!this.inputMessage.trim() || this.sending) {
					return
				}
				
				const messageContent = this.inputMessage.trim()
				const tempId = Date.now()
				
				// 创建临时消息对象
				const tempMessage = {
					id: tempId,
					fromUserId: this.userInfo.userId,
					toUserId: this.userId,
					content: messageContent,
					sendTime: new Date().toISOString(),
					status: 'sending'
				}
				
				// 添加到本地消息列表
				this.messages.push(tempMessage)
				this.inputMessage = ''
				this.sending = true
				this.hideEmojiPanel()
				this.hideMorePanel()
				this.scrollToBottom()
				
				try {
					// 1. 先通过HTTP API发送消息到服务器
					const result = await this.sendMessageAPI({
						toUserId: this.userId,
						content: messageContent
					})
					
					if (result.code === 200) {
						// HTTP发送成功，更新消息ID和状态
						const messageIndex = this.messages.findIndex(m => m.id === tempId)
						if (messageIndex > -1) {
							this.messages[messageIndex].id = result.data.id
							this.messages[messageIndex].status = 'sent'
							this.messages[messageIndex].sendTime = result.data.sendTime
						}

						// 注意：不需要通过WebSocket再次发送，服务器会自动推送给接收方
						// HTTP API已经处理了消息的存储和推送
						
					} else {
						throw new Error(result.message || '发送失败')
					}
					
				} catch (error) {
					console.error('发送消息失败:', error)
					
					// 更新消息状态为发送失败
					const messageIndex = this.messages.findIndex(m => m.id === tempId)
					if (messageIndex > -1) {
						this.messages[messageIndex].status = 'failed'
					}
					
					uni.showToast({
						title: error.message || '发送失败',
						icon: 'none'
					})
				} finally {
					this.sending = false
				}
			},
			
			/**
			 * 格式化时间（简短）
			 */
			formatTime(timeStr) {
				if (!timeStr) return ''
				
				const time = new Date(timeStr)
				return time.toLocaleTimeString('zh-CN', { 
					hour: '2-digit', 
					minute: '2-digit',
					hour12: false 
				})
			},
			
			/**
			 * 格式化详细时间（用于时间分割线）
			 */
			formatDetailTime(timeStr) {
				if (!timeStr) return ''
				
				const time = new Date(timeStr)
				const now = new Date()
				const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
				const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
				
				if (time >= today) {
					return '今天 ' + time.toLocaleTimeString('zh-CN', { 
						hour: '2-digit', 
						minute: '2-digit',
						hour12: false 
					})
				} else if (time >= yesterday) {
					return '昨天 ' + time.toLocaleTimeString('zh-CN', { 
						hour: '2-digit', 
						minute: '2-digit',
						hour12: false 
					})
				} else {
					return time.toLocaleDateString('zh-CN') + ' ' + time.toLocaleTimeString('zh-CN', { 
						hour: '2-digit', 
						minute: '2-digit',
						hour12: false 
					})
				}
			},
			
			/**
			 * 判断是否显示时间分割线
			 */
			shouldShowTime(message) {
				const messageIndex = this.messages.findIndex(m => m.id === message.id)
				if (messageIndex === 0) return true

				const prevMessage = this.messages[messageIndex - 1]
				if (!prevMessage) return true

				const currentTime = new Date(message.sendTime)
				const prevTime = new Date(prevMessage.sendTime)

				// 如果两条消息间隔超过10分钟，显示时间（减少时间显示频率）
				return (currentTime - prevTime) > 10 * 60 * 1000
			},
			
			scrollToBottom() {
				// 使用防抖，避免频繁滚动
				if (this.scrollTimer) {
					clearTimeout(this.scrollTimer)
				}
				this.scrollTimer = setTimeout(() => {
					this.$nextTick(() => {
						// 使用更精确的滚动位置计算
						const query = uni.createSelectorQuery().in(this)
						query.select('.message-list').scrollOffset((res) => {
							if (res) {
								this.scrollTop = res.scrollHeight
							} else {
								// 降级方案
								this.scrollTop = 999999
							}
						}).exec()
					})
				}, 16) // 减少延迟，提高响应速度
			},
			
			/**
			 * 标记会话为已读
			 */
			async markAsRead() {
				try {
					await markSessionAsRead(this.userId)

					// 通知聊天列表页面清除未读消息数
					uni.$emit('clearUnreadCount', {
						userId: this.userId
					})
				} catch (error) {
					console.error('标记会话已读失败:', error)
				}
			},
			
			/**
			 * 切换表情面板
			 */
			toggleEmojiPanel() {
				this.showEmojiPanel = !this.showEmojiPanel
			},
			
			/**
			 * 隐藏表情面板
			 */
			hideEmojiPanel() {
				this.showEmojiPanel = false
			},
			
			/**
			 * 隐藏更多面板
			 */
			hideMorePanel() {
				this.showMorePanel = false
			},
			
			/**
			 * 发送消息API调用
			 */
			async sendMessageAPI(data) {
				return await sendMessageAPI(data)
			},
			
			/**
			 * 插入表情
			 */
			insertEmoji(emoji) {
				this.inputMessage += emoji
			},

			/**
			 * 返回上一页
			 */
			goBack() {
				uni.navigateBack()
			},

			/**
			 * 显示聊天菜单
			 */
			showChatMenu() {
				this.showChatMenuModal = true
			},

			/**
			 * 隐藏聊天菜单
			 */
			hideChatMenu() {
				this.showChatMenuModal = false
			},

			/**
			 * 计算消息列表高度
			 */
			calculateMessageListHeight() {
				try {
					const systemInfo = uni.getSystemInfoSync()
					const headerHeight = 88 // 顶部导航高度
					const inputAreaHeight = 100 // 输入区域基础高度
					const statusBarHeight = systemInfo.statusBarHeight || 0

					this.messageListHeight = systemInfo.windowHeight - headerHeight - inputAreaHeight - statusBarHeight
				} catch (error) {
					console.error('计算消息列表高度失败:', error)
					this.messageListHeight = 600 // 设置默认高度
				}
			},

			/**
			 * 输入框聚焦
			 */
			onInputFocus() {
				this.showEmojiPanel = false
				this.showMorePanel = false
				this.calculateMessageListHeight()

				// 发送正在输入状态
				this.sendTypingStatus(true)
			},

			/**
			 * 输入框失焦
			 */
			onInputBlur() {
				this.calculateMessageListHeight()

				// 停止正在输入状态
				this.sendTypingStatus(false)
			},

			/**
			 * 发送输入状态
			 */
			sendTypingStatus(isTyping) {
				try {
					const wsMessage = {
						type: 'typing',
						toUserId: this.userId,
						fromUserId: this.userInfo.userId,
						isTyping: isTyping
					}
					sendWebSocketMessage(wsMessage)
				} catch (error) {
					console.log('发送输入状态失败:', error)
				}
			},

			/**
			 * 切换更多功能面板
			 */
			toggleMorePanel() {
				this.showMorePanel = !this.showMorePanel
				this.showEmojiPanel = false
				this.calculateMessageListHeight()
			},

			/**
			 * 切换表情面板
			 */
			toggleEmojiPanel() {
				this.showEmojiPanel = !this.showEmojiPanel
				this.showMorePanel = false
				this.calculateMessageListHeight()
			},

			/**
			 * 开始语音录制
			 */
			startVoiceRecord() {
				this.isRecordingVoice = true
				uni.showToast({
					title: '开始录音',
					icon: 'none'
				})
			},

			/**
			 * 结束语音录制
			 */
			endVoiceRecord() {
				this.isRecordingVoice = false
				uni.showToast({
					title: '录音结束',
					icon: 'none'
				})
			},

			/**
			 * 选择图片
			 */
			chooseImage() {
				this.showMorePanel = false
				uni.chooseImage({
					count: 1,
					success: (res) => {
						uni.showToast({
							title: '图片功能开发中',
							icon: 'none'
						})
					}
				})
			},

			/**
			 * 拍照
			 */
			takePhoto() {
				this.showMorePanel = false
				uni.showToast({
					title: '拍照功能开发中',
					icon: 'none'
				})
			},

			/**
			 * 选择视频
			 */
			chooseVideo() {
				this.showMorePanel = false
				uni.showToast({
					title: '视频功能开发中',
					icon: 'none'
				})
			},

			/**
			 * 选择文件
			 */
			chooseFile() {
				this.showMorePanel = false
				uni.showToast({
					title: '文件功能开发中',
					icon: 'none'
				})
			},

			/**
			 * 分享位置
			 */
			shareLocation() {
				this.showMorePanel = false
				uni.showToast({
					title: '位置功能开发中',
					icon: 'none'
				})
			},

			/**
			 * 发送语音
			 */
			sendVoice() {
				this.showMorePanel = false
				uni.showToast({
					title: '语音功能开发中',
					icon: 'none'
				})
			},

			/**
			 * 发送红包
			 */
			sendRedPacket() {
				this.showMorePanel = false
				uni.showToast({
					title: '红包功能开发中',
					icon: 'none'
				})
			},

			/**
			 * 转账
			 */
			transfer() {
				this.showMorePanel = false
				uni.showToast({
					title: '转账功能开发中',
					icon: 'none'
				})
			},



			/**
			 * 查看资料
			 */
			viewProfile() {
				this.hideChatMenu()
				uni.showToast({
					title: '查看资料功能开发中',
					icon: 'none'
				})
			},

			/**
			 * 清空聊天记录
			 */
			clearHistory() {
				this.hideChatMenu()
				uni.showModal({
					title: '确认清空',
					content: '确定要清空所有聊天记录吗？',
					success: (res) => {
						if (res.confirm) {
							this.messages = []
							uni.showToast({
								title: '已清空聊天记录',
								icon: 'success'
							})
						}
					}
				})
			},

			/**
			 * 设置背景
			 */
			setBackground() {
				this.hideChatMenu()
				uni.showToast({
					title: '设置背景功能开发中',
					icon: 'none'
				})
			}
		}
	}
</script>

<style scoped>
	/* 主容器 */
	.chat-detail {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: linear-gradient(180deg, #f8f9fa 0%, #e9ecef 100%);
		/* 性能优化 */
		will-change: auto;
		-webkit-transform: translateZ(0);
		transform: translateZ(0);
		-webkit-backface-visibility: hidden;
		backface-visibility: hidden;
	}

	/* 顶部导航栏 */
	.chat-header {
		background: #393a3f;
		padding-top: constant(safe-area-inset-top);
		padding-top: env(safe-area-inset-top);
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1000;
	}

	.header-content {
		display: flex;
		align-items: center;
		height: 88rpx;
		padding: 0 30rpx;
	}

	.header-left {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.back-icon {
		color: white;
		font-size: 60rpx;
		font-weight: 300;
	}

	.header-center {
		flex: 1;
		text-align: center;
	}

	.chat-title {
		color: white;
		font-size: 36rpx;
		font-weight: 500;
		display: block;
	}

	.online-status {
		color: rgba(255, 255, 255, 0.7);
		font-size: 24rpx;
		display: block;
		margin-top: 4rpx;
	}

	.header-right {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.more-icon {
		color: white;
		font-size: 40rpx;
		font-weight: bold;
	}

	/* 连接状态提示 - 已移除 */
	
	/* 消息列表 */
	.message-list {
		flex: 1;
		padding: 10rpx 0;
		margin-top: 88rpx;
		background: transparent;
		height: calc(100vh - 88rpx - 100rpx);
		padding-top: constant(safe-area-inset-top);
		padding-top: env(safe-area-inset-top);
		position: relative;
		/* 优化滚动性能 */
		will-change: scroll-position;
		-webkit-overflow-scrolling: touch;
		contain: layout style paint;
		/* 启用硬件加速 */
		transform: translateZ(0);
		-webkit-transform: translateZ(0);
		/* 优化渲染性能 */
		backface-visibility: hidden;
		-webkit-backface-visibility: hidden;
		/* 减少重绘 */
		overflow-anchor: auto;
	}

	/* 聊天背景 */
	.chat-background {
		position: fixed;
		top: 88rpx;
		left: 0;
		right: 0;
		bottom: 100rpx;
		background-image: url('https://img1.baidu.com/it/u=3602773692,1512483864&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500');
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
		opacity: 0.3;
		z-index: 0;
	}
	
	.load-more {
		text-align: center;
		padding: 20rpx;
	}

	.loading-indicator {
		display: inline-block;
		background: rgba(0, 0, 0, 0.1);
		border-radius: 20rpx;
		padding: 10rpx 20rpx;
	}

	.loading-text {
		color: #666;
		font-size: 24rpx;
	}
	
	.time-divider {
		text-align: center;
		margin: 20rpx 0;
	}

	.time-label {
		display: inline-block;
		background: rgba(0, 0, 0, 0.08);
		border-radius: 10rpx;
		padding: 6rpx 12rpx;
	}

	.time-text {
		color: #888;
		font-size: 20rpx;
	}
	
	.message-item {
		margin-bottom: 8rpx;
		position: relative;
		z-index: 1;
		/* 优化渲染性能 */
		contain: layout style;
		will-change: auto;
		/* 启用硬件加速 */
		transform: translateZ(0);
		-webkit-transform: translateZ(0);
		/* 减少动画，提升滚动性能 */
		/* animation: messageSlideIn 0.2s ease-out; */
	}

	@keyframes messageSlideIn {
		from {
			opacity: 0;
			transform: translateY(10rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.message-wrapper {
		display: flex;
		align-items: flex-end;
		margin-bottom: 8rpx;
		padding: 0 20rpx;
	}

	/* 自己的消息布局：右对齐 */
	.own-message-wrapper {
		justify-content: flex-end;
	}

	/* 对方的消息布局：左对齐 */
	.message-wrapper:not(.own-message-wrapper) {
		justify-content: flex-start;
	}

	.message-bubble {
		max-width: 65%;
		min-width: 80rpx;
		position: relative;
		transform: translateZ(0); /* 启用硬件加速 */
		transition: transform 0.15s ease;
	}

	.message-bubble:active {
		transform: scale(0.98) translateZ(0);
	}

	.message-content {
		padding: 16rpx 20rpx;
		border-radius: 20rpx;
		background: #f8f9fa;
		word-wrap: break-word;
		line-height: 1.35;
		font-size: 28rpx;
		position: relative;
		box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.08);
		border: 1rpx solid #e9ecef;
		z-index: 1;
		min-height: 40rpx;
		display: flex;
		align-items: center;
	}

	.own-bubble .message-content {
		background: linear-gradient(135deg, #007AFF 0%, #4A90E2 100%);
		color: white;
		border: none;
		box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.2);
	}
	
	/* 消息气泡尖角 */
	.message-content::before {
		content: '';
		position: absolute;
		top: 16rpx;
		left: -12rpx;
		width: 0;
		height: 0;
		border: 12rpx solid transparent;
		border-right-color: #f8f9fa;
		filter: drop-shadow(-1rpx 0 2rpx rgba(0, 0, 0, 0.06));
	}

	.own-bubble .message-content::before {
		left: auto;
		right: -12rpx;
		border-right-color: transparent;
		border-left-color: #007AFF;
		filter: drop-shadow(1rpx 0 2rpx rgba(0, 122, 255, 0.2));
	}

	.message-text {
		color: #333;
		font-size: 28rpx;
		line-height: 1.35;
		word-break: break-word;
		font-weight: 400;
		letter-spacing: 0.3rpx;
	}

	.own-bubble .message-text {
		color: white;
	}
	
	.message-status {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		margin-top: 4rpx;
		padding: 0 20rpx;
	}

	/* 自己消息的状态显示在右侧 */
	.message-status.own-status {
		justify-content: flex-end;
		margin-right: 0; /* 移除头像空间 */
	}

	.message-time {
		font-size: 18rpx;
		color: #aaa;
		margin-top: 2rpx;
	}

	.send-status {
		font-size: 18rpx;
		margin-left: 8rpx;
	}

	.status-sending {
		color: #aaa;
	}

	.status-failed {
		color: #ff4757;
	}

	.status-sent {
		color: #2ed573;
	}

	.status-read {
		color: #667eea;
	}
	
	.empty-messages {
		text-align: center;
		padding: 200rpx 0;
		color: #999;
	}
	
	.empty-tip {
		font-size: 24rpx;
		color: #ccc;
		margin-top: 20rpx;
		display: block;
	}
	
	/* 输入区域 */
	.input-area {
		background: rgba(255, 255, 255, 0.98);
		backdrop-filter: blur(20rpx);
		border-top: 1rpx solid rgba(0, 0, 0, 0.08);
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 1000;
		box-shadow: 0 -2rpx 16rpx rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
	}

	.input-area.panel-open {
		position: relative;
	}

	.input-wrapper {
		display: flex;
		align-items: flex-end;
		padding: 16rpx 20rpx;
		gap: 12rpx;
		transform: translateZ(0); /* 启用硬件加速 */
	}

	.function-btn {
		width: 64rpx;
		height: 64rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 18rpx;
		background: #f8f9fa;
		border: 1rpx solid #e9ecef;
		flex-shrink: 0;
		transition: all 0.2s ease;
		transform: translateZ(0); /* 启用硬件加速 */
	}

	.function-btn:active {
		transform: scale(0.95) translateZ(0);
	}

	.function-btn.active {
		background: #007AFF;
		border-color: #007AFF;
		box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.25);
	}

	.function-btn.active .function-icon {
		color: white;
	}

	.function-icon {
		font-size: 30rpx;
		color: #666;
		font-weight: 500;
	}

	.input-container {
		flex: 1;
		background: #f8f9fa;
		border-radius: 18rpx;
		border: 1rpx solid #e9ecef;
		min-height: 64rpx;
		max-height: 160rpx;
		transition: all 0.2s ease;
	}

	.input-container:focus-within {
		border-color: #007AFF;
		background: white;
		box-shadow: 0 0 0 3rpx rgba(0, 122, 255, 0.08);
	}

	.message-input {
		width: 100%;
		min-height: 64rpx;
		max-height: 160rpx;
		padding: 16rpx 18rpx;
		font-size: 28rpx;
		line-height: 1.35;
		background: transparent;
		border: none;
		resize: none;
		color: #333;
		font-weight: 400;
		letter-spacing: 0.3rpx;
		box-sizing: border-box;
	}

	.send-btn {
		width: 100rpx;
		height: 64rpx;
		background: linear-gradient(135deg, #007AFF 0%, #4A90E2 100%);
		border-radius: 18rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
		box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.2);
		transition: all 0.2s ease;
	}

	.send-btn:active {
		transform: scale(0.95) translateZ(0);
	}

	.send-btn.sending {
		background: #999;
		box-shadow: none;
	}

	.send-text {
		color: white;
		font-size: 24rpx;
		font-weight: 500;
		letter-spacing: 0.5rpx;
	}

	.voice-btn {
		width: 64rpx;
		height: 64rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background: #07c160;
		flex-shrink: 0;
	}

	.voice-icon {
		color: white;
		font-size: 32rpx;
	}
	
	.emoji-btn {
		width: 70rpx;
		height: 70rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		border-radius: 50%;
		background: #f5f5f5;
	}
	
	.emoji-btn text {
		font-size: 32rpx;
	}
	

	
	.send-btn.active {
		background: #667eea;
	}
	
	.send-btn:disabled {
		opacity: 0.6;
	}
	
	/* 表情面板 */
	.emoji-panel {
		background: #f7f7f7;
		border-top: 1rpx solid #e5e5e5;
		height: 400rpx;
	}

	.emoji-header {
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #e5e5e5;
	}

	.emoji-title {
		font-size: 28rpx;
		color: #666;
	}

	.emoji-scroll {
		height: 320rpx;
	}

	.emoji-grid {
		display: flex;
		flex-wrap: wrap;
		padding: 20rpx;
		gap: 20rpx;
	}

	.emoji-item {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 10rpx;
		background: white;
		transition: all 0.2s;
	}

	.emoji-text {
		font-size: 40rpx;
	}

	.emoji-item:active {
		background: #e5e5e5;
		transform: scale(0.95);
	}

	/* 更多功能面板 */
	.more-panel {
		background: #f7f7f7;
		border-top: 1rpx solid #e5e5e5;
		height: 400rpx;
	}

	.more-header {
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #e5e5e5;
	}

	.more-title {
		font-size: 28rpx;
		color: #666;
	}

	.more-grid {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 40rpx;
		padding: 40rpx;
	}

	.more-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 16rpx;
	}

	.more-icon-wrapper {
		width: 120rpx;
		height: 120rpx;
		background: white;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.more-icon {
		font-size: 60rpx;
	}

	.more-text {
		font-size: 24rpx;
		color: #666;
	}

	.more-item:active .more-icon-wrapper {
		background: #f0f0f0;
		transform: scale(0.95);
	}

	/* 聊天菜单弹窗 */
	.chat-menu-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.3);
		z-index: 2000;
		display: flex;
		align-items: flex-start;
		justify-content: flex-end;
		padding: 108rpx 30rpx 0 0;
	}

	.chat-menu {
		background: #4c4c4c;
		border-radius: 8rpx;
		overflow: hidden;
		min-width: 240rpx;
	}

	.chat-menu-item {
		display: flex;
		align-items: center;
		padding: 24rpx 30rpx;
		gap: 20rpx;
		border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
	}

	.chat-menu-item:last-child {
		border-bottom: none;
	}

	.chat-menu-item:active {
		background: rgba(255, 255, 255, 0.1);
	}

	.menu-icon {
		font-size: 32rpx;
		color: white;
	}

	.menu-text {
		color: white;
		font-size: 28rpx;
	}
</style>